﻿// See https://aka.ms/new-console-template for more information
using System.Diagnostics;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using AutoDeploy.Client;

public class Program
{
   
    static string _projectName;


    public static async Task<int> Main(string[] args)
    {
        Console.WriteLine("Hello, AutoDeploy!");
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        if (args.Length <1 )
        {
            //throw new Exception("请传入编译路径");
            Console.WriteLine("项目名");
            return 1;
        }
        foreach (string arg in args)
        {
            Console.WriteLine(arg);
        }

        _projectName = args[0];
        //read configs
        string jsonString = await File.ReadAllTextAsync("data.json");
        List<ProjectConfig> configs = JsonSerializer.Deserialize<List<ProjectConfig>>(jsonString)!;
        var currentConfig = configs.Single(t=>t.Name == _projectName);

        if (args.Length > 1)
        {
            currentConfig.PublishFolder = Path.GetFullPath(args[1]); //相对路径转绝对路径

        }
        if (string.IsNullOrEmpty(currentConfig.PublishFolder))
        {
            Console.WriteLine("请传入发布路径");
            return 1;
        }

        //log
        string logPath = "AutoDeploy.log";
        using StreamWriter writer = new StreamWriter(logPath);
        writer.WriteLine(currentConfig.PublishFolder);






        //1拿到最新发布的文件
        FileManager fileManager = new FileManager(currentConfig);
        var recentFiles = fileManager.GetLastestFiles(currentConfig.PublishFolder);
        if (recentFiles != null && recentFiles.Any())
        {
            ApiClient api = new ApiClient(currentConfig);

            foreach (var file in recentFiles)
            {
                writer.WriteLine($"文件: {file.FullName}, 创建时间: {file.CreationTime}");
                //2上传文件
               var msg = await api.UploadFileAsync(file.FullName, currentConfig.DeployFolder);
                writer.WriteLine(msg);
            }

            //3 pm2重启项目
            var result = await api.Pm2Execute(_projectName);
            writer.WriteLine(result);
        }






        stopwatch.Stop();
        writer.WriteLine($"done:{stopwatch.Elapsed.TotalSeconds}");
        return 0;


    }



    



}